import ReactDOM from "react-dom";
import React from "react";

export function openModal(Component, props, env, container) {
  if(container) {
    ReactDOM.unstable_renderSubtreeIntoContainer(env, <Component {...props}/>, container);
    return container;
  } else {
    let div = document.createElement('div');
    let body = document.body;
    body.appendChild(div);
    ReactDOM.unstable_renderSubtreeIntoContainer(env, <Component {...props}/>, div);
    return div;
  }
}

export function removeContainer(container) {
  ReactDOM.unmountComponentAtNode(container);
  let body = document.body;
  body.removeChild(container);
}

export function openModalDirect(Component, props, env) {
  let container;
  const targetProps = {
    visible: true,
    close: () => {
      openModal(Component, {
        ...targetProps,
        visible: false
      }, env, container);
    },
    afterClose: () => {
      props.afterClose && props.afterClose();
      removeContainer(container);
      container = null;
    },
    ...props
  };
  container = openModal(Component, targetProps, env);
}
